// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init()
const db = cloud.database();
const $ = db.command.aggregate;

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext();
  let source = event.source;
  let card_number = event.card_number;
  let card_password = event.card_password;
  let express_number = event.express_number;
  let card_id = event.card_id;
  let update_time = new Date();
  if (source == 'scan') {
    let card_info = await db.collection('ops_card').where({
      card_number: card_number,
      card_password: card_password,
    }).get();
    if (card_info.data.length == 0) {
      return "卡券不存在";
    } else {
      card_id = card_info.data[0]._id;
      Issuer_openid = card_info.data[0].Issuer_openid;
      if (Issuer_openid != wxContext.OPENID) {
        return "不是本账号所签发的卡券";
      } else {
        updateTable();
      }
    }
  } else {
    updateTable();
  };
  return 1;
  function updateTable() {
    // ops_card增加快递单号和更新时间
    db.collection('ops_card').where({
      _id: card_id,
    }).update({
      data: {
        express_number: express_number,
        status: 4, // 已发货
        update_time: update_time,
      },
    }).then(res => {
      // ops_order增加快递单号和更新时间
      db.collection('ops_order').where({
        card_id: card_id,
      }).update({
        data: {
          express_number: express_number,
          status: 2, // 已发货
          update_time: update_time,
        },
      }).catch(err => console.error(err));
    }).catch(err => console.error(err));
  }
}